<template>
  <view class="container">
    <!-- 图片滑动容器 -->
    <scroll-view
      class="image-scroll"
      scroll-y
      enhanced
      show-scrollbar="false"
      @scroll="onScroll"
      @scrolltoupper="onScrollToUpper"
      @scrolltolower="loadMoreImages"
      @touchstart="onTouchStart"
      @touchend="onTouchEnd"
      :scroll-with-animation="true"
      :scroll-top="scrollTop"
    >
      <view class="image-list">
        <!-- 图片项 -->
        <view 
          class="image-item" 
          v-for="(item, index) in imageList" 
          :key="item.id"
          :style="{ height: screenHeight + 'px' }"
        >
          <!-- 图片组件 -->
          <image
            :id="'image-' + index"
            :src="item.imageUrl"
            class="image-content"
            mode="cover"
            @click="toggleInfo"
          ></image>
          
          <!-- 图片信息层 -->
          <view class="image-info" :class="{ 'show-info': showInfo }">
            <!-- 左侧信息 -->
            <view class="image-info-left">
              <view class="image-title">{{ item.title }}</view>
              <view class="image-author">@{{ item.author }}</view>
              <view class="image-desc">{{ item.description }}</view>
            </view>
            
            <!-- 右侧操作按钮 -->
            <view class="image-actions">
              <view class="action-btn" @click.stop="handleLike(index)">
                <text class="iconfont icon-like" :class="{ 'liked': item.isLiked }"></text>
                <text class="action-text">{{ item.likes }}</text>
              </view>
              <view class="action-btn" @click.stop="handleComment(index)">
                <text class="iconfont icon-comment"></text>
                <text class="action-text">{{ item.comments }}</text>
              </view>
              <view class="action-btn" @click.stop="handleShare(index)">
                <text class="iconfont icon-share"></text>
                <text class="action-text">分享</text>
              </view>
              <view class="action-btn avatar-btn" @click.stop="handleAvatarClick(index)">
                <image :src="item.avatar" class="avatar" mode="widthFix"></image>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>
    
    <!-- 加载提示 -->
    <view class="loading" v-if="isLoading">
      <uni-loading-icon size="24" color="#ffffff"></uni-loading-icon>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 图片列表数据
      imageList: [],
      // 当前显示的图片索引
      currentIndex: 0,
      // 屏幕高度
      screenHeight: 0,
      // 滚动位置
      scrollTop: 0,
      // 开始触摸时的Y坐标
      startY: 0,
      // 开始触摸时的时间戳
      startTime: 0,
      // 滑动距离
      swipeDistance: 0,
      // 滑动速度
      swipeVelocity: 0,
      // 是否显示信息
      showInfo: true,
      // 加载状态
      isLoading: false,
      // 是否还有更多图片
      hasMore: true,
      // 分页游标
      nextCursor: 0,
      // 图片分类和内容模板
      imageCategories: [
        {type: '风景', prefix: '绝美', suffix: '，大自然的馈赠！'},
        {type: '美食', prefix: '诱人的', suffix: '，看着就流口水！'},
        {type: '动物', prefix: '可爱的', suffix: '，萌化了我的心！'},
        {type: '建筑', prefix: '壮观的', suffix: '，人类智慧的结晶！'},
        {type: '艺术', prefix: '创意', suffix: '，不一样的视觉体验'},
        {type: '人物', prefix: '街头抓拍', suffix: '，记录美好生活'}
      ]
    };
  },
  
  onLoad() {
    // 获取屏幕高度
    const sysInfo = uni.getSystemInfoSync();
    this.screenHeight = sysInfo.screenHeight;
    
    // 初始化加载图片
    this.loadMoreImages();
  },
  
  methods: {
    // 触摸开始
    onTouchStart(e) {
      this.startY = e.touches[0].clientY;
      this.startTime = Date.now();
      this.showInfo = false; // 滑动开始隐藏信息
    },
    
    // 触摸结束
    onTouchEnd(e) {
      // 计算滑动距离和速度
      const endY = e.changedTouches[0].clientY;
      const endTime = Date.now();
      this.swipeDistance = this.startY - endY; // 正值表示向上滑，负值表示向下滑
      const swipeTime = endTime - this.startTime;
      this.swipeVelocity = Math.abs(this.swipeDistance) / swipeTime;
      
      // 判断是否触发翻页
      const minDistance = 50; // 最小滑动距离阈值（降低至50px）
      const minVelocity = 0.5; // 最小滑动速度阈值
      
      let targetIndex = this.currentIndex;
      
      // 向上滑动（下一页）
      if ((this.swipeDistance > minDistance) || (this.swipeVelocity > minVelocity && this.swipeDistance > 0)) {
        targetIndex = Math.min(this.currentIndex + 1, this.imageList.length - 1);
      }
      // 向下滑动（上一页）
      else if ((this.swipeDistance < -minDistance) || (this.swipeVelocity > minVelocity && this.swipeDistance < 0)) {
        targetIndex = Math.max(this.currentIndex - 1, 0);
      }
      
      // 执行翻页
      if (targetIndex !== this.currentIndex) {
        this.scrollToIndex(targetIndex);
      } else {
        // 回到当前页
        this.scrollToIndex(this.currentIndex);
      }
      
      this.showInfo = true; // 滑动结束显示信息
    },
    
    // 滚动到指定索引的图片
    scrollToIndex(index) {
      if (index === this.currentIndex) return;
      
      this.currentIndex = index;
      // 计算精确的滚动位置
      this.scrollTop = index * this.screenHeight;
      
      // 如果接近列表底部，加载更多
      if (index >= this.imageList.length - 2) {
        this.loadMoreImages();
      }
    },
    
    // 处理滚动事件（仅用于监测）
    onScroll(e) {
      // 计算当前可见的主要页面索引
      const currentIndex = Math.floor(e.detail.scrollTop / this.screenHeight);
      
      // 更新当前索引
      if (currentIndex !== this.currentIndex && currentIndex < this.imageList.length) {
        this.currentIndex = currentIndex;
      }
    },
    
    // 加载更多图片
    async loadMoreImages() {
      if (this.isLoading || !this.hasMore) return;
      
      this.isLoading = true;
      
      try {
        const res = await this.fetchImages();
        this.imageList = this.imageList.concat(res.images);
        this.nextCursor = res.nextCursor;
        this.hasMore = res.hasMore;
      } catch (err) {
        console.error('加载图片失败:', err);
        uni.showToast({ title: '加载失败', icon: 'none' });
      } finally {
        this.isLoading = false;
      }
    },
    
    // 生成模拟图片数据
    fetchImages() {
      return new Promise(resolve => {
        setTimeout(() => {
          const images = [];
          
          for (let i = 0; i < 5; i++) {
            const id = this.nextCursor + i;
            const category = this.imageCategories[Math.floor(Math.random() * this.imageCategories.length)];
            const titles = [
              `${category.prefix}${category.type}摄影 ${id+1}${category.suffix}`,
              `精选${category.type}作品 ${id+1}${category.suffix}`,
              `绝美${category.type}瞬间 ${id+1}${category.suffix}`,
              `${category.type}爱好者必看 ${id+1}${category.suffix}`
            ];
            
            const descriptions = [
              "大家觉得这张照片怎么样？欢迎在评论区告诉我~",
              "喜欢这张照片的话别忘了点赞关注哦！",
              "下期想看什么类型的照片？评论区告诉我吧",
              "拍摄于去年夏天，满满的回忆"
            ];
            
            const randomTitle = titles[Math.floor(Math.random() * titles.length)];
            const randomDesc = descriptions[Math.floor(Math.random() * descriptions.length)];
            
            images.push({
              id,
              title: randomTitle,
              author: `${category.type}摄影师${id % 20 + 1}`,
              description: randomDesc,
              avatar: `https://picsum.photos/seed/avatar${id}/100/100`,
              imageUrl: `https://picsum.photos/seed/${category.type}${id}/800/1400`,
              likes: Math.floor(Math.random() * 10000),
              comments: Math.floor(Math.random() * 1000),
              isLiked: false
            });
          }
          
          resolve({
            images,
            nextCursor: this.nextCursor + 5,
            hasMore: this.nextCursor < 30
          });
        }, 800);
      });
    },
    
    // 滚动到顶部
    onScrollToUpper() {
      this.scrollToIndex(0);
    },
    
    // 切换信息显示状态
    toggleInfo() {
      this.showInfo = !this.showInfo;
    },
    
    // 处理点赞
    handleLike(index) {
      if (this.imageList[index].isLiked) {
        this.imageList[index].likes--;
      } else {
        this.imageList[index].likes++;
      }
      this.imageList[index].isLiked = !this.imageList[index].isLiked;
    },
    
    // 处理评论
    handleComment(index) {
      uni.showToast({ title: `查看${this.imageList[index].title}的评论`, icon: 'none' });
    },
    
    // 处理分享
    handleShare(index) {
      uni.showToast({ title: `分享${this.imageList[index].title}`, icon: 'none' });
    },
    
    // 处理头像点击
    handleAvatarClick(index) {
      uni.showToast({ title: `进入${this.imageList[index].author}的主页`, icon: 'none' });
    }
  }
};
</script>

<style scoped>
.container {
  width: 100%;
  height: 100%;
  background-color: #000;
  overflow: hidden;
}

.image-scroll {
  width: 100%;
  height: 100%;
  /* 增强滚动体验 */
  -webkit-overflow-scrolling: touch;
  scroll-snap-type: y mandatory;
  overscroll-behavior-y: contain; /* 防止滚动溢出 */
}

.image-list {
  width: 100%;
}

.image-item {
  position: relative;
  width: 100%;
  overflow: hidden;
  display: block;
  scroll-snap-align: center; /* 居中对齐，更容易看到翻页效果 */
  scroll-snap-stop: always;
}

.image-content {
  width: 100%;
  height: 100%;
}

.image-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  color: #fff;
  display: flex;
  justify-content: space-between;
  transition: opacity 0.3s ease;
  opacity: 0;
}

.image-info.show-info {
  opacity: 1;
}

.image-info-left {
  flex: 1;
  max-width: 70%;
  padding-bottom: 100rpx;
}

.image-title {
  font-size: 34rpx;
  font-weight: bold;
  margin-bottom: 15rpx;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.5);
  line-height: 1.4;
}

.image-author {
  font-size: 28rpx;
  color: #eee;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.5);
  margin-bottom: 10rpx;
}

.image-desc {
  font-size: 26rpx;
  color: #ddd;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.5);
  line-height: 1.3;
}

.image-actions {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 30rpx;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10rpx;
  transition: transform 0.2s;
}

.action-btn:active {
  transform: scale(0.9);
}

.iconfont {
  font-size: 50rpx;
}

.icon-like.liked {
  color: #ff3b30;
}

.action-text {
  font-size: 24rpx;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  border: 2rpx solid #fff;
}

.loading {
  position: fixed;
  bottom: 80rpx;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  padding: 20rpx;
  border-radius: 50rpx;
}
</style>
    